package com.dreamoo.common.exception;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常工具类
 * 
 * @author dreamoo
 */
public class ExceptionUtil {
    
    /**
     * 获取异常的堆栈信息
     * 
     * @param throwable 异常
     * @return 堆栈信息
     */
    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            throwable.printStackTrace(pw);
            return sw.toString();
        } finally {
            pw.close();
        }
    }
    
    /**
     * 获取异常的根本原因
     * 
     * @param throwable 异常
     * @return 根本原因
     */
    public static Throwable getRootCause(Throwable throwable) {
        Throwable cause = throwable.getCause();
        if (cause == null) {
            return throwable;
        }
        return getRootCause(cause);
    }
    
    /**
     * 获取异常的根本原因消息
     * 
     * @param throwable 异常
     * @return 根本原因消息
     */
    public static String getRootCauseMessage(Throwable throwable) {
        Throwable rootCause = getRootCause(throwable);
        return rootCause.getMessage();
    }
    
    /**
     * 判断异常是否由某种类型的异常引起
     * 
     * @param throwable     异常
     * @param causeClass    异常类型
     * @return 是否由该类型异常引起
     */
    public static boolean isCausedBy(Throwable throwable, Class<? extends Throwable> causeClass) {
        if (throwable == null) {
            return false;
        }
        if (causeClass.isInstance(throwable)) {
            return true;
        }
        Throwable cause = throwable.getCause();
        if (cause == throwable) {
            return false;
        }
        return isCausedBy(cause, causeClass);
    }
} 